//$URL: http://dasding.googlecode.com/svn/trunk/api/src/main/java/de/piratech/dasding/api/rest/ActionCategoryResource.java $
//$Id: ActionCategoryResource.java 130 2013-04-19 19:47:34Z krieg.maria@gmail.com $
/*
 * Copyright 2012 Piratech.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.piratech.dasding.api.rest;

import de.piratech.dasding.data.ActionCategory;
import de.piratech.dasding.data.User;
import de.piratech.dasding.data.database.DatabaseException;
import de.piratech.dasding.security.annotations.RequireUserRole;
import java.util.List;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * Resource for action category requests
 * <p>
 * Those include:
 * <p>
 * GET: load all categories<br>
 * PUT: update category<br>
 * POST: create category<br>
 * DELETE: delete category (only valid for unverified categories)<br>
 * <p>
 * 
 * @author deveth0
 * @since 0.4
 */
@Path("/actions/categories")
@Component
public class ActionCategoryResource extends AbstractResource {

  private static final Logger LOG = LoggerFactory
      .getLogger(ActionCategoryResource.class);

  /**
   * Returns all action categories
   * 
   * http://localhost:8080/dasding.api/api/actions/categories
   * 
   * GET
   * 
   * @return
   */
  @GET
  @Path("find")
  @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
  public List<ActionCategory> getActionCategories() {
    LOG.debug("getActionCategories()");
    try {
      return getActionCategoryData().getVerifiedCategories();
    } catch (DatabaseException dbe) {
      throw getBadRequestException(dbe);
    }
  }

  /**
   * Returns all action categories
   * 
   * http://localhost:8080/dasding.api/api/actions/categories/{categoryid}
   * 
   * GET
   * 
   * @return
   */
  @GET
  @Path("/{categoryid}")
  @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
  public ActionCategory getActionCategory(
      @PathParam("categoryid") String pCategoryId) {
    LOG.debug("getActionCategories()");
    try {
      return getActionCategoryData().getActionCategory(pCategoryId);
    } catch (DatabaseException dbe) {
      throw getBadRequestException(dbe);
    }
  }

  /**
   * update actioncategory
   * 
   * http://localhost:8080/dasding.api/api/actions/categories/{categoryid}
   * 
   * PUT
   * 
   * @param pName
   *          (required)
   * @param pDescription
   *          (required)
   * 
   * @return
   */
  @PUT
  @Path("/{categoryid}")
  @RequireUserRole(roles = User.USER_ROLE.USER)
  public Response updateActionCategory(
      @PathParam("categoryid") String pCategoryId,
      @QueryParam("name") String pName,
      @QueryParam("description") String pDescription,
      @QueryParam("verified") Boolean pVerified,
      @Context SecurityContext pSecurityContext) {
    LOG.debug("createActionCategory(name={}, description={}, verified={})",
        pName, pDescription);
    try {
      User user = getUserFromSecurityContext(pSecurityContext);
      ActionCategory actionCategory = getActionCategoryData()
          .getActionCategory(pCategoryId);
      // can only be modified by the user who created it or by an admin
      if (!user.hasRole(User.USER_ROLE.ADMIN)
          || StringUtils.equals(actionCategory.getCreatedBy().getId(),
              user.getId())) {
        return getForbiddenResponse();
      }
      if (actionCategory == null) {
        return getBadRequestResponse("id invalid");
      }
      if (StringUtils.isNotBlank(pName)) {
        actionCategory.setName(pName);
      }
      if (StringUtils.isNotBlank(pDescription)) {
        actionCategory.setDescription(pDescription);
      }
      if (pVerified != null && user.hasRole(User.USER_ROLE.VERIFIED_USER)) {
        LOG.debug("Setting actionCategory {} to verfied={}", pCategoryId,
            pVerified);
        actionCategory.setVerified(pVerified);
      }
      if (!actionCategory.isValid()) {
        return getBadRequestResponse();
      }
      getActionCategoryData().updateActionCategory(actionCategory);
      return getNoContentResponse();
    } catch (DatabaseException dbe) {
      return getBadRequestResponse(dbe);
    }
  }

  /**
   * deletes actioncategory
   * 
   * http://localhost:8080/dasding.api/api/actions/categories/{categoryid}
   * 
   * DELETE
   * 
   * @param pCategoryId
   *          (required)
   * 
   * @return
   */
  @DELETE
  @Path("/{categoryid}")
  @RequireUserRole(roles = User.USER_ROLE.ADMIN)
  public Response deleteActionCategory(
      @PathParam("categoryid") String pCategoryId,
      @Context SecurityContext pSecurityContext) {
    LOG.debug("deleteActionCategory({})", pCategoryId);
    try {
      getActionCategoryData().deleteActionCategory(
          getActionCategoryData().getActionCategory(pCategoryId));
      return getNoContentResponse();
    } catch (DatabaseException dbe) {
      return getBadRequestResponse(dbe);
    }
  }

  /**
   * Creates a new actioncategory
   * 
   * http://localhost:8080/dasding.api/api/actions/categories
   * 
   * POST
   * 
   * @param pName
   *          (required)
   * @param pDescription
   *          (required)
   * 
   * @return
   */
  @POST
  @RequireUserRole(roles = User.USER_ROLE.USER)
  public Response createActionCategory(@QueryParam("name") String pName,
      @QueryParam("description") String pDescription,
      @Context SecurityContext pSecurityContext) {
    LOG.debug("createActionCategory(name={}, description={})", pName,
        pDescription);
    ActionCategory actionCategory = new ActionCategory();
    actionCategory.setName(pName);
    actionCategory.setDescription(pDescription);
    User user = getUserFromSecurityContext(pSecurityContext);
    if (user.hasRole(User.USER_ROLE.VERIFIED_USER)) {
      LOG.debug("User is verified, setting ActionCategory to verified=true");
      actionCategory.setVerified(true);
    }
    actionCategory.setCreatedBy(user);
    if (!actionCategory.isValid()) {
      return getBadRequestResponse();
    }
    try {
      actionCategory = getActionCategoryData().createActionCategory(
          actionCategory);
      return getCreatedResponse("/" + actionCategory.getId());
    } catch (DatabaseException dbe) {
      return getBadRequestResponse(dbe);
    }
  }

  @Override
  protected Logger getLogger() {
    return LOG;
  }
}
